'use strict'

/**
 * The set of field types.
 * Please see the document of type.
 *
 * @public
 * @type {Object}
 */
let Types = require('./type');

/**
 * The module to operate models.
 * Please see the document of model.
 *
 * @public
 * @type {Object}
 */
let model = require('./model');

/**
 * The base class of all models.
 * Please see the document of model.
 *
 * @public
 * @type {class<model/base/Model>}
 */
let BaseModel = require('./model/base').Model;

/**
 * The flag to specify whether the persistent module is enabled.
 *
 * @private
 */
let _isPersistEnabled = false;

/**
 * Enable persistent module for unique model.
 *
 * @public
 *
 * @example
 * enablePersist();
 */
function enablePersist() {
    _isPersistEnabled = true;
}

/**
 * Check whether the persistent is enabled for unique model.
 *
 * @public
 *
 * @return {Boolean}   The status of persistent module.
 *                      Return true if the persistent module is enabled.
 *                      Return false if the persistent module is disabled.
 *
 * @example
 * let result = isPersistEnabled(); 
 * if ( result ) {
 *    console.log('The persistent module is enabled');
 * }
 */
function isPersistEnabled() {
    return _isPersistEnabled;
}

/**
 * Create the persistent session for unique model.
 *
 * @public
 *
 * @param {Object} options - The options of session
 * @param {String} options.backend - The backend name
 * @param {String} options.uri - The uri passed to backend
 * @param {Object} options.options - The other options passed to backend
 *
 * @return {Session}    The persistent session object.
 *                      Return null if the persistent module is disabled.
 *
 * @example
 * um.enablePersist();
 * let session = um.createSession({
 *     backend: 'mongodb',
 *     uri: 'mongodb://localhost/userman',
 *     options: {
 *         user: 'user',
 *         pass: '123456'
 *     }
 * });
 */
function createSession(options) {
    if ( !isPersistEnabled() ) {
        return null;
    }
    
    let backend = require('./backend/' + options.backend);
    let Session = require('./session').Session;
    let backendSession = new backend.Session({
        uri: options.uri,
        options: options.options
    });

    return new Session(backendSession);
}

module.exports = {
    Types,
    BaseModel,
    model,
    enablePersist,
    isPersistEnabled,
    createSession
};
